var jsdom = require('jsdom');
var fs = require('fs');
var util = require('../lib/util.html.js');
var args = process.argv.slice(2);
var filename = args[0];
var saveFilename = args[1];
var content = fs.readFileSync(filename, {
    encoding: 'utf8'
});
var contents = JSON.parse(content);
for (var i = 0, len = contents.length; i < len; i++) {
    var item = contents[i];
    var chapter = item.data;
    var title = chapter.title;
    var html = chapter.content;
    var parsedHtml = html.replace(/<br\s*\/>/gi, '\n');
    jsdom.env(html, (function(title, html) {
        return function(errors, window) {
            var $ = window.$;
            var targetTxt = util.getPlainText(window.document.body);
            var chapterTxt = title + '\n' + targetTxt + '\n\n';
            fs.writeFileSync(saveFilename, chapterTxt, {
                encoding: 'utf8',
                flag: 'a'
            });
        }
    })(title, html));
}
